'use strict';

const jwt = require('jsonwebtoken');
// const uuid = require("uuid");
// const CryptoJS = require("crypto-js");
// console.log("---------uuidv4()--------")
// let _pubKey = uuid.v4();
//  console.log("_pubKey:",_pubKey)
//  console.log("---------uuidv4()--------")
//  let key = CryptoJS.enc.Utf8.parse(_pubKey); //16位
//  let iv = CryptoJS.enc.Utf8.parse(_pubKey);
//  let data = JSON.stringify({a:1,b:2});
//  let srcs = CryptoJS.enc.Utf8.parse(data);
//  let encrypted = CryptoJS.AES.encrypt(srcs, key, {
//      iv: iv,
//      mode: CryptoJS.mode.CBC,
//      padding: CryptoJS.pad.Pkcs7
//  })
//  console.log("xxxxxxxxxxx加密后xxxxxxxxxxxxx")
//  console.log(encrypted.toString())
//  console.log("xxxxxxxxxxxxxxxxxxxxxxxx")
//  let decrypted =CryptoJS.AES.decrypt(encrypted.toString(),key,
//      {
//          iv:iv,
//          mode:CryptoJS.mode.CBC,
//          padding:CryptoJS.pad.Pkcs7
//      });

//      console.log("xxxxxxxxxxx解密后xxxxxxxxxxxxx")
//      console.log(decrypted.toString(CryptoJS.enc.Utf8)   )
//      console.log("xxxxxxxxxxxxxxxxxxxxxxxx")
const _priKey = `-----BEGIN RSA PRIVATE KEY-----
                MIICWwIBAAKBgQDGNrzOW3wuyy88mWM5C5pWXhP5IukJUu3j7cUnYHGsCQeuH2Dj
                YXnub583DWeaUN1hpNPHvAXfXj8Zl8/E/VZv3NLyejs4o6g1wCP1msTRKubJwznX
                Lza6tnwAo6/IjpnR5/ngOSdsPtz8QYcpC9VF4MZA35uaZLBqUwzBkI3gSwIDAQAB
                AoGAWL2W6BhjT5veCRZvKtH8BiDWdlrf1DHRmZMRCmEOY0QjsRwRR5uTeGF2+bHB
                qX/8rUObITgXtPo/69hgx8PYFzEEuUh/5Z/9Lk8Ky2X6OgnxWjHX4qzRudYeFu0i
                c/JF4Mh/oSkAS/u1rNxQEpj6lKo5Q7gNBZK9jJRC9aHc6AkCQQDpZqVw5e119+D7
                N/XefUopCsqwWwz5Llj5tiQdOZrXwgOmlGltbn8DFhTbJVJSn2fc8zL9ymXKcCyF
                JkA1LEkHAkEA2WfmoRgYcZIoUnmprs+wgHkY7tFiPyNcyqwmA46pAm3bjI79QEsC
                Znipc9zllyWAlKjwbrgoyEG7CSfmaU9xnQJAd9b+h3Nnc7TszdCz66NFGsGxxM9b
                X+5OPRkqfd8ABFxX54Y4g7nCeWEzIDqPhGDYwXgV7H2pukHSeiNjwGmWrQJAJb9f
                kOrxG48IB0Huj1aqS7Q6+wRJ7bKDIwF+3DFB8RUIAMC3AhnEAezDZ0Wca4DscWNf
                06mQEy0uf2l5HSHZFQJAYaTZwR4vhv4YxlE8dy7fhEijzlWIkBn4BdP+8rZiEf9c
                zMbeB5BGGPcseGt08EqK1wYPjh5N3nEUumS/KkFAfQ==
                -----END RSA PRIVATE KEY-----`;
module.exports = (options, app) => {
    return async function userInterceptor(ctx, next) {
        try{
            let headerData = ctx.request.header;
            if(headerData._token){
                // token验证
                var decoded = jwt.decode( headerData._token, _priKey );
                 
                if(decoded){
                    let timeData = parseInt(new Date().getTime() / 1000);
                    if (decoded && decoded.exp > timeData) {
                        ctx.request.body._token = jwt.verify(headerData._token, _priKey).data; 
                        await next();
                    } else {
                        ctx.body = { errCode: 600003, success: false, msg: '无效签名，请重新登录' };
                    }
                }else{
                    ctx.body = { errCode: 600002, msg: '非法请求，无效token!' };
                }
            }else{
                ctx.body = { errCode: 600001, success: false, msg: '非法请求，无效token！' };
            }
        }catch(err){
            console.log('sync function userInterceptor-error', err);
            if(err.name == "TokenExpiredError"){
                ctx.body = { errCode: 900002, success: false, msg: '无效token，请重新登录！', data: err };
            }else{
                ctx.body = { errCode: 900001, success: false, msg: '请求失败，未知错误！', data: err };
            }
        }
    }
}

